package com.mor.shiro.test.thead.lock;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.LockSupport;

public class Spinlock {

    private volatile int status = 0;

    BlockingDeque<Thread> blockingDeque =new LinkedBlockingDeque<>();

    public void lock() {
        while (!compareAndSet(0, 1)) {
            System.out.println(Thread.currentThread().getName()+"park");
            blockingDeque.add(Thread.currentThread());
            //暂让cpu使用权
            LockSupport.park();
        }
    }

    public void unlock() {
        Thread temp = blockingDeque.poll();
        LockSupport.unpark(temp);
        status = 0;
        System.out.println(Thread.currentThread().getName()+"执行结束，释放锁");
    }


    private boolean compareAndSet(int except, int now) {
        if (except == status) {
            status=now;
            System.out.println(Thread.currentThread().getName()+"修改了status的值"+status);
            return true;
        } else {
            System.out.println(Thread.currentThread().getName()+"修改了status的值失败");
            return false;
        }
    }
}